import React,{ useEffect, useState} from 'react';
import { useLocation } from 'react-router-dom';
import ReactPlayer from 'react-player';
import { useResultContext } from '../contexts/ResultContextProvider';
export const Results = () => {
const {getResults, results, isLoading, searchTerm} = useResultContext();
const location = useLocation();
const [num, setNum] = useState(10);
const changeNum=()=>{
setNum(num+10);
console.log(num)
Results();
}
useEffect(()=>{
if(searchTerm){
if (location.pathname ==='/videos') {
getResults(`/search/q=${searchTerm} videos&num=${num}`)
}else{
getResults(`${location.pathname}/q=${searchTerm}&num=${num}`)
}
}
},[location.pathname, searchTerm, num, getResults]);
switch (location.pathname) {
case '/search':
return (<><div className='flex flex-wrap justify-between space-y-6 sm:px-56 overflow-hidden pb-4 '>
{
results?.results?.map(({link, title, description}, index)=>(
<div key={index} className='md:w-3/5 w-full'>
<a href={link} target="_blank" rel="noreferrer">
<p className='text-sm text-green-700'>
{link.length>50? link.substring(0,50): link}
</p>
<p className='text-lg hover:underline dark:text-blue-300 text-blue-700'>
{title}
</p>
</a>
{description.length>15?
<p>
{description}
</p>:''}
</div>
))
}
</div>
<div onClick={changeNum} className='absolute bg-gray-200 border border-gray-400 py-3 px-10 rounded-full -mt-5 left-96 cursor-pointer active:bg-gray-300 dark:bg-gray-700 '>
More Results
</div>
</>);
default: return 'ERROR';
}
};
I've started learning react and it's been two days i have been unable to get around this.
I'm trying to make google search engine clone and in this project i'm getting results using google search api and displaying 10 results at first and want then to increase by 10 every time when i click on 'More Results' button which calls 'changeNum' function which uses 'setNum' to add 10 value to 'num' every time function is called by clicking on button.
EDIT: i shortened the code by removing some cases
const changeNum=()=>{
setNum(num+10);
console.log(num)
Results(); <--------
}
Calling your functional component like this is what is causing the error. This line is not needed as your component will update when you update the state.